/**
 * @author 铭
 * @TODO 9/1/2024
 */
package com.woniuxy.service.impl;

import com.woniuxy.daos.TbUserDao;
import com.woniuxy.entitys.TbCustomer;
import com.woniuxy.entitys.TbUser;
import com.woniuxy.entitys.TbUserExample;
import com.woniuxy.service.UserLoginService;
import com.woniuxy.utils.JWTUtils;
import com.woniuxy.utils.LoginCustomer;
import com.woniuxy.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Resource
    private TbUserDao tbUserDao;
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public TbUser login(TbUser user) {
        TbUserExample tbUserExample = new TbUserExample();
        TbUserExample.Criteria criteria = tbUserExample.createCriteria();
        criteria.andPhoneEqualTo(user.getPhone());
        criteria.andUpwdEqualTo(user.getUpwd());

        List<TbUser> tbUsers = tbUserDao.selectByExample(tbUserExample);
        if (tbUsers.size()!=0){
            return tbUsers.get(0);

        }
        return null;
    }

    @Override
    public void deleteToken(String token) {
        String username = jwtUtils.getUsername(token);
        redisTemplate.delete("user:"+username);
    }



    @Override
    public Integer updPwd(String oldPwd, String newPwd) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String header = servletRequestAttributes.getRequest().getHeader("token");
        String username = jwtUtils.getUsername(header);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        LoginUser loginUser = (LoginUser) valueOperations.get("user:" + username);

        TbUser user = loginUser.getUser();
        System.out.println("**************" + user);
        if (!user.getUpwd().equals(oldPwd)){
            return 0;
        }
        user.setUpwd(newPwd);

        return tbUserDao.updateByPrimaryKeySelective(user);
    }

}
